<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    chartData: {
      type: Object,
      default: () => ({
        ageRanges: ['<20', '20~30', '30~40', '40~50', '>50'],
        values: [20, 30, 25, 15, 10]
      })
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ ageRanges, values } = this.chartData) {
      // 创建半圆形的多层环形图
      const series = [];
      const color = '#36d1ff';
      const radius = [40, 52, 64, 76, 88];

      for (let i = 0; i < ageRanges.length; i++) {
        series.push({
          name: ageRanges[i],
          type: 'pie',
          radius: [`${radius[i]}%`, `${radius[i] + 8}%`],
          center: ['40%', '50%'],
          startAngle: 180,
          endAngle: 0,
          clockwise: false,
          hoverAnimation: false,
          itemStyle: {
            color: color,
            borderWidth: 0
          },
          label: {
            show: false
          },
          data: [
            { value: values[i], name: ageRanges[i] },
            { 
              value: 100 - values[i], 
              name: 'invisible', 
              itemStyle: { 
                color: 'rgba(30, 50, 70, 0.2)',
                borderWidth: 0
              },
              tooltip: { show: false }
            }
          ]
        });
      }

      this.chart.setOption({
        legend: {
          orient: 'vertical',
          right: '15%',
          top: 'center',
          itemGap: 12,
          itemWidth: 10,
          itemHeight: 10,
          data: ageRanges,
          textStyle: {
            color: '#36d1ff',
            fontSize: 14,
            padding: [0, 0, 0, 5] // 调整文字与图标的间距
          },
          itemStyle: {
            opacity: 1
          }
        },
        tooltip: {
          show: false
        },
        series: series
      });
    }
  }
}
</script>
